import * as roleApi from '@/api/role-management';
const state = {
  roleList: {},
  roleDetailsList: {
    roleIds: [],
  },
  // 获取编辑的角色详情
  roleDetails: {},
  // 获取权限列表
  jurisdictionList: []
}

const mutations = {
  SET_ROLE_LIST(state, newValue) {
    state.roleList = newValue
  },
  SET_ROLE_DETAILS_LIST(state, newValue) {
    state.roleDetailsList = newValue
  },
  SET_ROLE_DETAILS(state, newValue) {
    state.roleDetails = newValue
  },
  SET_JURISDICTION_LIST(state, newValue) {
    state.jurisdictionList = newValue
  },

}

const actions = {
  async updateRoleList ({commit}, params) {
    const res = await roleApi.roleList(params);
    commit('SET_ROLE_LIST', res)
  },
  async updateRoleDetailsList ({commit}, id) {
    const res = await roleApi.roleDetails(id);
    commit('SET_ROLE_DETAILS_LIST', res)
  },
  async updateRoleDetails ({commit}, id) {
    const res = await roleApi.getRole(id);
    commit('SET_ROLE_DETAILS', res)
  },
  async updateJurisdictionList ({commit}) {
    const res = await roleApi.getJurisdiction();
    commit('SET_JURISDICTION_LIST', res)
  },
}

function dataTransfer(data, pid) {
  const arr =  data.filter(d => d.pid === pid).map(d => ({
      ...d,
      children: dataTransfer(data, d.id)
    }))
    return arr
}

const getters = {
  getJurisdictionTree(state) {
    return dataTransfer(state.jurisdictionList, '0')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
